package com.demo.test.other;

/**
 * 人员聚集 计算余弦距离
 * @author 86153
 */
public class CosineDistance {

    // 计算余弦距离
    public static double cos(String desFeature, String feature) {
        double[] vector1 = stringToDoubleArray(desFeature);
        double[] vector2 = stringToDoubleArray(feature);
        return cosineDistance(vector1, vector2);
    }

    // 计算向量的模长（长度）
    public static double vectorLength(double[] vector) {
        double sum = 0.0;
        for (double value : vector) {
            sum += value * value;
        }
        return Math.sqrt(sum);
    }

    // 计算两个向量的点积
    public static double dotProduct(double[] vector1, double[] vector2) {
        double sum = 0.0;
        for (int i = 0; i < vector1.length; i++) {
            sum += vector1[i] * vector2[i];
        }
        return sum;
    }

    // 计算两个向量的余弦距离
    public static double cosineDistance(double[] vector1, double[] vector2) {
        double dotProduct = dotProduct(vector1, vector2);
        double vectorLength1 = vectorLength(vector1);
        double vectorLength2 = vectorLength(vector2);

        // 计算余弦距离
        if (vectorLength1 == 0 || vectorLength2 == 0) {
            return 0.0; // 避免除零错误
        } else {
            return dotProduct / (vectorLength1 * vectorLength2);
        }
    }

    public static double[] stringToDoubleArray(String input) {
        String[] parts = input.split(",");
        double[] result = new double[parts.length];

        for (int i = 0; i < parts.length; i++) {
            result[i] = Double.parseDouble(parts[i]);
        }
        return result;
    }


}